package com.jiangtai.smartbox.ui

import android.content.Intent
import android.util.Log
import com.google.gson.reflect.TypeToken
import com.hjq.toast.ToastUtils
import com.jiangtai.smartbox.R
import com.jiangtai.smartbox.base.BaseActivity
import com.jiangtai.smartbox.bean.request.PersonInfoBean
import com.jiangtai.smartbox.bean.request.SearchSuccessReq
import com.jiangtai.smartbox.bean.response.FaceInfoBean
import com.jiangtai.smartbox.net.CallbackListObserver
import com.jiangtai.smartbox.net.MyRetrofit
import com.jiangtai.smartbox.net.ThreadSwitchTransformer
import com.jiangtai.smartbox.util.DateUtil
import com.jiangtai.smartbox.util.ToJsonUtil
import kotlinx.android.synthetic.main.activity_put_watch.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import org.litepal.LitePal
import showToast

/**
 * Created by heCunCun on 2021/5/20
 */
class PutWatchActivity:BaseActivity() {
    override fun attachLayoutRes(): Int = R.layout.activity_put_watch

    override fun initData() {

    }

    override fun initView() {

    }

    private var searching = false
    override fun initListener() {
        tv_finish.setOnClickListener {
            finish()
        }
        iv_open.setOnClickListener {
            val packageManager = packageManager
            val intent = packageManager.getLaunchIntentForPackage("com.tongyue.facerecognition")
            startActivity(intent)

            //轮询查询识别成功的人 识别成功后  调到成功页
            val startTime = DateUtil.getCurrentTime()
            //循环查接口
            searching = true
            checkResult(startTime)

        }
    }

    private fun checkResult(startTime: String) {
        val bean = SearchSuccessReq(DateUtil.getCurrentTime(), 1, 1, startTime)
        val requestBody =
            RequestBody.create(
                "application/json; charset=utf-8".toMediaTypeOrNull(),
                ToJsonUtil.getInstance().toJson(
                    bean
                )
            )
        val searchCheckedSuccessPersonList =
            MyRetrofit.instance.api.searchCheckedSuccessPersonList(requestBody)
        searchCheckedSuccessPersonList.compose(ThreadSwitchTransformer()).subscribe(object :
            CallbackListObserver<String>() {
            override fun onSucceed(t: String?) {
                val listType = object : TypeToken<List<FaceInfoBean?>?>() {}.type
                val list = ToJsonUtil.getInstance().fromJson<List<FaceInfoBean>>(
                    t,listType)
                if (list.isNotEmpty()){
                    searching = false//识别成功
                    //识别的人是哪个
                    val faceInfoBean = list.last()
                    Log.e("Face","人脸信息id==${faceInfoBean.uid},人名==${faceInfoBean.name}")
                    //找到这个人的取表记录   有的话就开柜
                    val perList = LitePal.where("uid=?", faceInfoBean.uid.toString())
                        .find(PersonInfoBean::class.java)
                    if (perList.isNotEmpty()){
                        val personInfoBean = perList[0]
                        Log.e("Face","personId=${personInfoBean.personId}")
                        if (personInfoBean.takeState == 1){
                            val intent = Intent(this@PutWatchActivity,BoxOpenSuccessActivity::class.java)
                            intent.putExtra("personId",personInfoBean.personId)
                            intent.putExtra("takeWatch",false)
                            startActivity(intent)
                        }else{
                            ToastUtils.show("未在此柜取表,请到取表处还表")
                        }

                    }else{
                        ToastUtils.show("识别失败,没有此人的信息")
                    }
                }
                if (searching) {
                    checkResult(startTime)
                }

            }

            override fun onFailed() {
                Log.e("check", "识别onFailed")

            }


        })
    }

}